package com.hns.phone.pushMsg.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.hns.phone.pushMsg.enumrate.MsgStatus;
import com.hns.phone.pushMsg.vo.MessageStatusVo;
import com.hns.tool.pub.PubUtil;

/**
 * 推送基类
 * @author:zhangyu
 * @email:zhangyu2222z@sina.cn
 * @version Revision 2.0.0
 */
@Component
public class BasePushClient {
	
	private static final Logger logger = LoggerFactory.getLogger(BasePushClient.class);
	
	protected String appkey = null;
	protected String appMasterSecret = null;
	protected String timestamp = null;
	
	// The user agent
//	protected final String USER_AGENT = "Mozilla/5.0";

	// This object is used for sending the post request to Umeng
	protected HttpClient client = null;//new DefaultHttpClient();
		
	// The host
	protected static final String host = "http://msg.umeng.com";
		
	// The upload path
	protected static final String uploadPath = "/upload";
		
	// The post path
	protected static final String postPath = "/api/send";
	
	// the status path
	protected static final String statusPath = "/api/status";
	
//	private PushClient client = new PushClient();
	
	/**
	 * 推送
	 * @author:zhangyu
	 * @email:zhangyu2222z@sina.cn
	 */
	public String sendMsg(UmengNotification msg) throws Exception {
		String url = host + postPath;
		JSONObject respJson = send(msg, url);
        JSONObject data = respJson.getJSONObject("data");
        logger.error("推送返回的数据："+data);
        String taskId = "";
        if(data.has("task_id") && PubUtil.isNotEmpty(data.getString("task_id"))){
        	taskId = data.getString("task_id");
        }
        if(data.has("msg_id") && PubUtil.isNotEmpty(data.getString("msg_id"))){
        	taskId = data.getString("msg_id");
        }
        return taskId;
    }

	/**
	 * 发送
	 * @param msg
	 * @param url
	 * @return
	 * @throws Exception
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @author:zhangyu
	 * @email:zhangyu2222z@sina.cn
	 */
	private JSONObject send(UmengNotification msg, String url) throws Exception {
		client = new DefaultHttpClient();
		String timestamp = Integer.toString((int)(System.currentTimeMillis() / 1000));
		msg.setPredefinedKeyValue("timestamp", timestamp);
		String postBody = msg.getPostBody();
		StringBuffer result = sendAndDecode(url, postBody, msg.getAppMasterSecret());
		JSONObject respJson = new JSONObject(result.toString());
		return respJson;
	}
	
	private StringBuffer sendAndDecode(String url, String postBody, String appSecret) throws Exception{
		String sign = DigestUtils.md5Hex(("POST" + url + postBody + appSecret).getBytes("utf8"));
		logger.error("加密："+sign);
		logger.error("加密2："+"POST" + url + postBody + appSecret);
		url = url + "?sign=" + sign;
		HttpPost post = new HttpPost(url);
		StringEntity se = new StringEntity(postBody, "utf8");
		post.setEntity(se);
		HttpResponse response = client.execute(post);
		int status = response.getStatusLine().getStatusCode();
		logger.error("发送状态码："+status);
		if (status == 200) {
			System.out.println("发送成功！");
		    logger.error("发送成功！");
		} else {
			System.out.println("发送失败！");
		    logger.error("发送失败！");
		}
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
		    result.append(line);
		}
		return result;
	}
	
	
	/**
	 * 获取消息状态
	 * @author:zhangyu
	 * @email:zhangyu2222z@sina.cn
	 */
	public synchronized MessageStatusVo getMsgStatus(String appkey, String appMasterSecret, String taskId) throws Exception {
		String url = host + statusPath;
		
		JSONObject rootJson = new JSONObject();
		
		client = new DefaultHttpClient();
		String timestamp = Integer.toString((int)(System.currentTimeMillis() / 1000));
		rootJson.put("appkey", appkey);
		rootJson.put("timestamp", timestamp);
		rootJson.put("task_id", taskId);
		
		StringBuffer result = sendAndDecode(url, rootJson.toString(), appMasterSecret);
		
		JSONObject respJson = new JSONObject(result.toString());
        JSONObject data = respJson.getJSONObject("data");
        logger.error("返回的数据:"+data);
		MessageStatusVo statusResult = new MessageStatusVo();
		if(data.has("status")){
			MsgStatus[] values = MsgStatus.values();
			MsgStatus  msgStatus = values[data.getInt("status")];
			statusResult.setStatus(msgStatus.getDsc());
		}
        statusResult.setTotalCount(data.getInt("total_count"));
        statusResult.setAcceptCount(data.getInt("accept_count"));
        statusResult.setSendCount(data.getInt("sent_count"));
        statusResult.setOpenCount(data.getInt("open_count"));
        statusResult.setDismissCount(data.getInt("dismiss_count"));
        return statusResult;
	}
}
